<script setup>
	import { ref, onMounted, watch } from 'vue'
	import { useUserStore } from '@/store/userInfo'

	const userStore = useUserStore( )
	const productApi = uniCloud.importObject( 'product' )
	const cateApi = uniCloud.importObject( 'cate' )

	// 防抖函数
	const showToastDebounced = ( ( ) => {
		let timer = null
		return ( options ) => {
			if ( timer ) clearTimeout( timer )
			timer = setTimeout( ( ) => {
				uni.showToast( options )
			}, 300 )
		}
	} )( )

	// 商品列表数据
	const productList = ref( [ ] )
	// 分类列表
	const cateList = ref( [ ] )
	// 弹窗引用
	const popup = ref( null )
	// 是否编辑模式
	const isEdit = ref( false )
	// 表单数据
	const formData = ref( {
		name: '',
		cate_id: '',
		cover_pic: '',
		banner_pic: [],
		buy_price: '',
		original_price: '',
		discount: '',
		sku: [ ]
	} )

	// 添加图片上传相关的响应式数据
	const imageValue = ref( [ ] )
	const bannerImages = ref( [ ] )

	// 获取分类列表
	const getCateList = async ( ) => {
		try {
			const result = await cateApi.get( )
			cateList.value = result.data
		} catch ( e ) {
			showToastDebounced( {
				title: '获取分类失败',
				icon: 'none'
			} )
		}
	}

	// 获取商品列表
	const getProductList = async ( ) => {
		try {
			const result = await productApi.getList( )
			productList.value = result.data
		} catch ( e ) {
			showToastDebounced( {
				title: '获取商品列表失败',
				icon: 'none'
			} )
		}
	}

	// 打开新增商品弹窗
	const handleAdd = ( ) => {
		isEdit.value = false
		formData.value = {
			name: '',
			cate_id: '',
			cover_pic: '',
			banner_pic: [],
			buy_price: '',
			original_price: '',
			discount: '',
			sku: [ ]
		}
		imageValue.value = [ ]
		bannerImages.value = [ ]
		popup.value.open( )
	}

	// 打开编辑商品弹窗
	const handleEdit = ( item ) => {
		isEdit.value = true
		formData.value = { ...item }
		// 设置图片值，需要转换为 uni-file-picker 需要的格式
		imageValue.value = item.cover_pic ? [ {
			url: item.cover_pic,
			fileID: item.cover_pic,
			name: item.cover_pic.split( '/' ).pop( ),
		} ] : [ ]
		// 设置轮播图值
		bannerImages.value = item.banner_pic ? item.banner_pic.map( pic => ({
			url: pic,
			fileID: pic,
			name: pic.split( '/' ).pop( )
		} ) ) : [ ]
		popup.value.open( )
	}

	// 删除商品
	const handleDelete = async ( id ) => {
		try {
			const res = await uni.showModal( {
				title: '提示',
				content: '确定要删除该商品吗？',
				confirmColor: '#ff4d4f'
			} )

			if ( !res.confirm ) return

			const result = await productApi.remove( id, userStore.userInfo.role[ 0 ] )
			if ( result.errCode === 0 ) {
				showToastDebounced( {
					title: '删除成功',
					icon: 'success'
				} )
				getProductList( )
			} else {
				showToastDebounced( {
					title: result.errMsg,
					icon: 'none'
				} )
			}
		} catch ( e ) {
			showToastDebounced( {
				title: '删除失败',
				icon: 'none'
			} )
		}
	}

	// 监听价格变化，自动计算折扣
	watch(
		[
			( ) => formData.value.buy_price,
			( ) => formData.value.original_price
		],
		( [ newBuyPrice, newOriginalPrice ] ) => {
			if ( newBuyPrice && newOriginalPrice ) {
				// 计算折扣并四舍五入到整数
				const discount = Math.round( ( Number( newBuyPrice ) / Number( newOriginalPrice ) ) * 100 )
				formData.value.discount = discount > 100 ? 100 : discount
			} else {
				formData.value.discount = 100
			}
		}
	)

	// 提交表单
	const submitForm = async ( ) => {
		if ( !formData.value.name || !formData.value.cate_id || !formData.value.buy_price || !
			formData.value.cover_pic ) {
			showToastDebounced( {
				title: '请填写完整信息',
				icon: 'none'
			} )
			return
		}

		try {
			// 处理表单数据，转换价格类型
			const submitData = {
				...formData.value,
				buy_price: Number( formData.value.buy_price ),
				original_price: Number( formData.value.original_price || formData.value.buy_price ),
				discount: Number( formData.value.discount || 100 )
			}

			const result = isEdit.value ?
				await productApi.update( submitData, userStore.userInfo.role[ 0 ] ) :
				await productApi.add( submitData, userStore.userInfo.role[ 0 ] )

			if ( result.errCode === 0 ) {
				popup.value.close( )
				setTimeout( ( ) => {
					showToastDebounced( {
						title: '成功',
						icon: 'success'
					} )
				}, 500 )
				getProductList( )
			} else {
				setTimeout( ( ) => {
					showToastDebounced( {
						title: result.errMsg,
						icon: 'none'
					} )
				}, 500 )
			}
		} catch ( e ) {
			showToastDebounced( {
				title: '失败',
				icon: 'none'
			} )
		}
	}

	// 添加 uni-file-picker 的相关方法
	const select = ( e ) => {
		console.log( '选择文件：', e )
	}

	const progress = ( e ) => {
		console.log( '上传进度：', e )
	}

	const success = ( e ) => {
		console.log( '上传成功：', e )
		formData.value.cover_pic = e.tempFiles[ 0 ].url || e.tempFiles[ 0 ].fileID
		showToastDebounced( {
			title: '上传成功',
			icon: 'success'
		} )
	}

	const fail = ( e ) => {
		console.error( '上传失败：', e )
		showToastDebounced( {
			title: '上传失败',
			icon: 'none'
		} )
	}

	// 轮播图上传成功
	const bannerSuccess = ( e ) => {
		const fileInfo = e.tempFiles[ 0 ]
		formData.value.banner_pic.push( fileInfo.url )
	}

	// 轮播图删除
	const bannerDelete = ( e ) => {
		const deleteIndex = e.index
		formData.value.banner_pic.splice( deleteIndex, 1 )
	}

	onMounted( ( ) => {
		getCateList( )
		getProductList( )
	} )
</script>

<template>
	<view class="product-list">
		<!-- 商品列表 -->
		<view class="list">
			<view class="item" v-for="item in productList" :key="item._id">
				<view class="product-info">
					<image class="cover" :src="item.cover_pic" mode="aspectFill" />
					<view class="info">
						<view class="name">{{ item.name }}</view>
						<view class="cate">
							分类：{{ cateList.find(cate => cate._id === item.cate_id)?.cate_name || '-' }}
						</view>
						<view class="price">
							<text class="buy-price">¥{{ item.buy_price }}</text>
							<text class="original-price">¥{{ item.original_price }}</text>
						</view>
						<view class="actions">
							<button class="btn edit" @tap="handleEdit(item)">编辑</button>
							<button class="btn delete" @tap="handleDelete(item._id)">删除</button>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部安全区域占位 -->
		<view class="safe-area"></view>

		<!-- 添加商品按钮 -->
		<view class="add-btn" @tap="handleAdd">
			<uni-icons custom-prefix="iconfont" type="yuan-tianjia" color="#fff" :size="24" />
			<text>新增商品</text>
		</view>

		<!-- 添加/编辑商品弹窗 -->
		<uni-popup ref="popup" type="center" :safe-area="true" :mask-click="true">
			<view class="popup-content">
				<view class="popup-header">
					<text class="title">{{ isEdit ? '编辑商品' : '添加商品' }}</text>
					<text class="close" @tap="popup.close()">×</text>
				</view>
				<scroll-view class="popup-scroll" scroll-y>
					<view class="form-item">
						<text class="label">商品名称</text>
						<input type="text" v-model="formData.name" placeholder="请输入商品名称" />
					</view>
					<view class="form-item">
						<text class="label">商品分类</text>
						<picker :range="cateList" range-key="cate_name"
							@change="e => formData.cate_id = cateList[e.detail.value]._id">
							<view class="picker">
								{{ cateList.find(cate => cate._id === formData.cate_id)?.cate_name || '请选择分类' }}
							</view>
						</picker>
					</view>
					<view class="form-item">
						<text class="label">售价</text>
						<input type="digit" v-model="formData.buy_price" placeholder="请输入售价" />
					</view>
					<view class="form-item">
						<text class="label">原价</text>
						<view class="price-row">
							<input type="digit" v-model="formData.original_price" placeholder="请输入原价" />
							<text class="discount" v-if="formData.discount && formData.discount !== 100">
								{{ formData.discount }}折
							</text>
						</view>
					</view>
					<view class="form-item">
						<text class="label">商品封面</text>
						<uni-file-picker v-model="imageValue" fileMediatype="image" mode="grid" :limit="1"
							:image-styles="{
								width: 160,
								height: 160,
							}" @select="select" @progress="progress" @success="success" @fail="fail" />
					</view>
					<view class="form-item">
						<text class="label">商品轮播图</text>
						<uni-file-picker v-model="bannerImages" fileMediatype="image" mode="grid" :limit="5"
							:image-styles="{
								width: 160,
								height: 160,
							}" @select="select" @progress="progress" @success="bannerSuccess" @delete="bannerDelete" />
						<text class="tip">最多上传5张轮播图</text>
					</view>
				</scroll-view>
				<view class="popup-buttons">
					<button class="btn cancel" @tap="popup.close()">取消</button>
					<button class="btn confirm" @tap="submitForm">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<style lang="scss" scoped>
	.product-list {
		min-height: 100vh;
		padding: 24rpx;
		padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
		background-color: $page-bg-color;

		.list {
			.item {
				margin-bottom: 24rpx;
				padding: 24rpx;
				background-color: #fff;
				border-radius: 16rpx;

				.product-info {
					display: flex;

					.cover {
						width: 160rpx;
						height: 160rpx;
						border-radius: 8rpx;
						margin-right: 24rpx;
					}

					.info {
						flex: 1;

						.name {
							font-size: 28rpx;
							color: $text-font-color-1;
							font-weight: 600;
							margin-bottom: 16rpx;
						}

						.cate {
							font-size: 24rpx;
							color: $text-font-color-2;
							margin-bottom: 16rpx;
						}

						.price {
							margin-bottom: 16rpx;

							.buy-price {
								font-size: 28rpx;
								color: #ff4d4f;
								margin-right: 16rpx;
							}

							.original-price {
								font-size: 22rpx;
								color: $text-font-color-3;
								text-decoration: line-through;
							}
						}

						.actions {
							display: flex;
							align-items: center;
							margin-left: auto;
							width: fit-content;

							.btn {
								padding: 8rpx 24rpx;
								border-radius: 8rpx;
								font-size: 22rpx;
								line-height: 1.5;
								background-color: transparent;

								&:not(:last-child) {
									margin-right: 24rpx;
								}

								&::after {
									border: none;
								}

								&.edit {
									color: $brand-theme-color;
									border: 2rpx solid $brand-theme-color;
								}

								&.delete {
									color: #ff4d4f;
									border: 2rpx solid #ff4d4f;
								}

								&:active {
									opacity: 0.8;
								}
							}
						}
					}
				}
			}
		}

		.safe-area {
			height: 120rpx;
			width: 100%;
		}

		.add-btn {
			position: fixed;
			right: 48rpx;
			bottom: calc(48rpx + constant(safe-area-inset-bottom));
			bottom: calc(48rpx + env(safe-area-inset-bottom));
			display: flex;
			align-items: center;
			padding: 24rpx 48rpx;
			background-color: $brand-theme-color;
			border-radius: 44rpx;
			color: #fff;
			box-shadow: 0 4rpx 16rpx rgba(70, 176, 254, 0.3);

			text {
				margin-left: 12rpx;
				font-size: 24rpx;
			}

			&:active {
				opacity: 0.8;
			}
		}
	}

	.popup-content {
		position: relative;
		z-index: 999;
		width: 680rpx;
		max-height: 80vh;
		background-color: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		padding: 0;
		display: flex;
		flex-direction: column;

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 24rpx;
			min-height: 90rpx;
			border-bottom: 2rpx solid $line-color-aux;
			background: #fff;

			.title {
				font-size: 32rpx;
				font-weight: 600;
				color: $text-font-color-1;
			}

			.close {
				font-size: 48rpx;
				color: $text-font-color-3;
				line-height: 1;
				padding: 0 12rpx;
				cursor: pointer;

				&:active {
					opacity: 0.8;
				}
			}
		}

		.popup-scroll {
			flex: 1;
			overflow-y: auto;
			-webkit-overflow-scrolling: touch;
			padding: 24rpx;
			background: #fff;
			
			/* 适配移动端滚动 */
			&::-webkit-scrollbar {
				display: none;
			}

			.form-item {
				margin-bottom: 24rpx;

				.label {
					display: block;
					margin-bottom: 12rpx;
					font-size: 26rpx;
					color: $text-font-color-2;
				}

				.tip {
					margin-top: 8rpx;
					font-size: 24rpx;
					color: $text-font-color-3;
				}

				input {
					width: 100%;
					height: 80rpx;
					padding: 0 24rpx;
					background-color: $page-bg-color;
					border-radius: 8rpx;
					font-size: 24rpx;
					box-sizing: border-box;
				}

				.picker {
					width: 100%;
					height: 80rpx;
					line-height: 80rpx;
					padding: 0 24rpx;
					background-color: $page-bg-color;
					border-radius: 8rpx;
					font-size: 24rpx;
					box-sizing: border-box;
				}

				.price-row {
					display: flex;
					align-items: center;
					gap: 12rpx;

					input {
						flex: 1;
					}

					.discount {
						font-size: 22rpx;
						color: #ff4d4f;
						padding: 4rpx 12rpx;
						background-color: #fff1f0;
						border-radius: 4rpx;
					}
				}
			}
		}

		.popup-buttons {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 24rpx;
			gap: 24rpx;
			border-top: 2rpx solid $line-color-aux;
			background: #fff;

			.btn {
				flex: 1;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 0;
				border-radius: 8rpx;
				font-size: 24rpx;

				&.cancel {
					background-color: $page-bg-color;
					color: $text-font-color-2;
				}

				&.confirm {
					background-color: $brand-theme-color;
					color: #fff;
				}

				&:active {
					opacity: 0.8;
				}
			}
		}
	}

	/* 自定义滚动条样式 */
	:deep(.popup-scroll::-webkit-scrollbar) {
		width: 6rpx;
	}

	:deep(.popup-scroll::-webkit-scrollbar-thumb) {
		border-radius: 3rpx;
		background-color: $text-font-color-3;
	}

	:deep(.popup-scroll::-webkit-scrollbar-track) {
		background-color: transparent;
	}

	// 添加 uni-file-picker 相关样式
	:deep(.uni-file-picker) {
		.is-add {
			border: 2rpx dashed $text-font-color-3;
		}
	}
</style>